<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="searchForm" :inline="true" :model="formRepairs">

      <el-form-item size="small" label="小区">
        <el-select v-model="formRepairs.communityId" placeholder="请选择" @change="loadZyRepairs(true)">
          <el-option
            v-for="item in community"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item size="small" label="业主姓名" prop="ownerRealName">
        <el-input v-model="formRepairs.ownerRealName" placeholder="请输入业主姓名" />
      </el-form-item>

      <el-form-item size="small" label="业主电话" prop="ownerPhoneNumber">
        <el-input v-model="formRepairs.ownerPhoneNumber" placeholder="请输入业主电话" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" size="mini" icon="el-icon-search" @click="loadZyRepairs(true)">
          查询
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetForm('searchForm')">重置</el-button>

      </el-form-item>

    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <!--隐藏搜索+刷新-->
      <right-toolbar
        :show-search.sync="showSearch"
        @queryTable="loadZyRepairs(true)"
      />
    </el-row>

    <el-table
      ref="multipleTable"
      :data="repairs"
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
      />

      <el-table-column
        label="序号"
        width="60"
        type="index"
        :index="indexMethod"
        align="center"
      />

      <el-table-column
        label="报修编号"
        width="160"
      >
        <template slot-scope="scope">{{ scope.row.repairNum }}</template>
      </el-table-column>

      <el-table-column
        label="报修状态"
        width="120"
        prop="repairState"
        :formatter="repairStatusFormat"
      />

      <el-table-column

        label="业主姓名"
        width="100"
      >
        <template slot-scope="scope">{{ scope.row.ownerRealName }}</template>
      </el-table-column>
      <el-table-column
        prop="name"
        label="业主电话"
        width="120"
        show-overflow-tooltip
      >
        <template slot-scope="scope">{{ scope.row.ownerPhoneNumber }}</template>
      </el-table-column>
      <el-table-column
        prop="name"
        label="报修内容"
        width="120"
      >
        <template slot-scope="scope">{{ scope.row.repairContent }}</template>
      </el-table-column>
      <el-table-column
        prop="address"
        label="详情地址"
        width="100"
      >
        <template slot-scope="scope">{{ scope.row.address }}</template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
      >
        <template slot-scope="scope">{{ scope.row.createTime }}</template>
      </el-table-column>
      <el-table-column
        prop="address"
        label="期待上门时间"
        door-time
      >
        <template slot-scope="scope">{{ scope.row.doorTime }}</template>
      </el-table-column>

      <el-table-column
        prop="address"
        label="处理人姓名"
      >

        <template slot-scope="scope">{{ scope.row.completeName }}</template>

      </el-table-column>

      <el-table-column
        prop="address"
        label="备注"
        show-overflow-tooltip
      >

        <template slot-scope="scope">{{ scope.row.remark }}</template>
      </el-table-column>

      <!--      <el-table-column label="查看详情">-->
      <!--        <template slot-scope="scope">-->
      <!--          <el-button-->
      <!--            size="mini"-->
      <!--            @click="handleEdit(scope.$index, scope.row)"-->
      <!--          >查看详情-->
      <!--          </el-button>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--    </el-table>-->
      <el-table-column label="进度审核">
        <template slot-scope="scope">
          <el-button
            type="warning"
            size="mini"
            @click="processCheck(scope.$index, scope.row)"
          >进度审核
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 查看详细对话框-->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose"
    >

      <el-form :inline="true" :model="repair" :label-position="labelPosition" class="demo-form-inline">
        <el-col :span="12">
          <el-form-item label="业主姓名">
            <el-select v-model="repair.ownerId" :disabled="flag" placeholder="请选择" clearable filterable style="width: 94%">
              <el-option
                v-for="item,index in ownerList"
                :key="index"
                :label="item.ownerRealName"
                :value="item.ownerId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="小区名称">
            <el-select v-model="repair.communityId" placeholder="请选择小区" clearable filterable style="width: 94%">
              <el-option
                v-for="item,index in communityList"
                :key="index"
                :label="item.communityName"
                :value="item.communityId"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <!--        <el-col :span="12">-->
        <!--          <el-form-item label="报修编号">-->
        <!--            <el-input v-model="repair.repairNum" disabled="true" placeholder="报修编号" style="width: 100%" />-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->

        <!--        <el-col :span="12">-->
        <!--          <el-form-item label="派单时间">-->
        <!--            <el-date-picker-->
        <!--              v-model="repair.assignmentTime"-->
        <!--              placeholder="请选择派单时间"-->
        <!--              clearable-->
        <!--              type="datetime"-->
        <!--              format="yyyy-MM-dd HH:mm:ss"-->
        <!--              value-format="yyyy-MM-dd HH:mm:ss"-->
        <!--            />-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->

        <el-col :span="12">
          <el-form-item label="报修内容">
            <el-input v-model="repair.repairContent" :disabled="flag" placeholder="报修内容" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="详细地址">
            <el-input v-model="repair.address" :disabled="flag" placeholder="详细地址" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="分派人员">
            <!--            <el-input v-model="repair.assignmentId" placeholder="请选择分派人员" />-->
            <el-select v-model="repair.assignmentId" placeholder="请选择分派人员" clearable filterable style="width: 94%">
              <el-option
                v-for="item,index in sysUserList"
                :key="index"
                :label="item.userName"
                :value="item.userId"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="处理人员">
            <!--            <el-input v-model="repair.completeName" placeholder="请选择实际处理人" />-->
            <el-select v-model="repair.completeId " placeholder="请选择实际处理人" clearable filterable style="width: 94%">
              <el-option
                v-for="item,index in sysUserList"
                :key="index"
                :label="item.userName"
                :value="item.userId"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="处理电话">
            <el-input v-model="repair.completePhone" placeholder="请输入处理人电话" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="其他电话">
            <el-input v-model="repair.otherPhone" placeholder="请输入其他电话" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="报修备注">
            <el-input v-model="repair.remark" placeholder="备注" />
          </el-form-item>
        </el-col>

        <!--        <el-col :span="12">-->
        <!--          <el-form-item label="保修状态" prop="repairState">-->
        <!--            &lt;!&ndash;            <el-input v-model="repair.repairState" placeholder="保修状态"></el-input>&ndash;&gt;-->
        <!--            <template>-->
        <!--              <el-select v-model="value" placeholder="请选择">-->
        <!--                <el-option-->
        <!--                  v-for="item in Coptions"-->
        <!--                  :key="item.value"-->
        <!--                  :label="item.label"-->
        <!--                  :value="item.value"-->
        <!--                />-->
        <!--              </el-select>-->
        <!--            </template>-->
        <!--          </el-form-item>-->

        <!--        </el-col>-->
        <!--        <el-col :span="12">-->
        <!--          <el-form-item label="完成时间">-->
        <!--            <el-date-picker-->
        <!--              v-model="repair.completeTime"-->
        <!--              placeholder="请选择处理完成时间"-->
        <!--              clearable-->
        <!--              type="datetime"-->
        <!--              format="yyyy-MM-dd HH:mm:ss"-->
        <!--              value-format="yyyy-MM-dd HH:mm:ss"-->
        <!--            />-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->

        <el-col :span="12">
          <el-form-item label="预期完成">
            <el-date-picker
              v-model="repair.doorTime"
              placeholder="请选择期待完成时间"
              clearable
              type="datetime"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
            />
          </el-form-item>
        </el-col>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveForm()">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>

      </span>
    </el-dialog>

    <!--    进度审核框-->
    <el-dialog title="进度审核" :visible.sync="progressVisible" width="60%">
      <el-timeline>
        <el-timeline-item
          v-for="item, index in timeLineDataList"
          :key="index"
          :timestamp="item.timestamp"
          placement="top"
          :color="item.color"
          size="large"
        >
          <el-card>
            <h4>{{ item.title }}</h4>
            <p>{{ item.content }}</p>
            <p v-if="item.attachContent">{{ item.attachContent }}</p>
            <el-button v-if="item.buttonVisible" :type="item.clickFlag === 'No_Processed'? 'danger' : 'success'" size="small" @click="processUpdate(item.clickFlag)">
              {{ item.buttonName }}
            </el-button>
          </el-card>
        </el-timeline-item>
      </el-timeline>
    </el-dialog>

    <div class="block" style="text-align:center">
      <el-pagination
        :current-page="current"
        :page-sizes="[ 3, 6, 9,12]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

  </div>
</template>

<script>
import { listCommunity } from '@/api/community'
import { get_one_uuid } from '@/utils/uuid'
import index from '@vue/test-utils'

export default {
  name: 'Repair',
  data() {
    return {
      labelPosition: 'left',
      showSearch: true,
      Coptions: [{
        value: 'Pending',
        label: '待处理',
        sort: 1,
        buttonName: '任务分派',
        clickFlag: 'Allocated'
      }, {
        value: 'Allocated',
        label: '已分派',
        sort: 2,
        buttonName: '任务处理',
        clickFlag: 'Processing'
      }, {
        value: 'Processing',
        label: '处理中',
        sort: 3,
        buttonName: '报修完成',
        clickFlag: 'Processed'
      }, {
        value: 'Processed',
        label: '已处理',
        sort: 4
      }, {
        value: 'No_Processed',
        label: '不处理',
        sort: 5,
        buttonName: '报修取消',
        clickFlag: 'No_Processed'
      }
      // {
      //   value: 'Cancelled',
      //   label: '已取消',
      //   sort: 6
      // }
      ],

      zyRepair: [],
      zyOwner: [],
      total: 0, // 共多少条
      current: 1, // 当前页数
      pageSize: 3, // 分页大小

      repair: {
        repairId: '',
        repairNum: '',
        repairState: '',
        assignmentTime: '',
        receivingOrdersTime: '',
        completeTime: '',
        cancelTime: '',
        doorTime: '',
        assignmentId: '',
        completeId: '',
        completePhone: '',
        otherPhone: '',
        completeName: '',
        remark: '',
        createBy: '',
        createTime: '',
        updateBy: '',
        updateTime: '',
        userId: '',
        delFlag: '',
        repairContent: '',
        communityId: '',
        address: '',
        zyOwner: {}

      },
      dialogVisible: false,

      repairs: [], // 表格数据
      multipleSelection: [],
      formRepairs: {
        communityId: '',
        ownerRealName: '',
        ownerPhoneNumber: ''
      },
      value: '',
      flag: false,
      title: '',
      community: [],
      ownerList: [],
      communityList: [],
      sysUserList: [],
      progressVisible: false,
      timeLineDataList: []
    }
  },
  created() {
    this.loadZyRepairs()
    this.communityAll()
  },
  methods: {
    index() {
      return index
    },
    // 查询业主信息
    queryOwnerList(realName) {
      const zyOwnerVO = {
        ownerRealName: realName
      }

      this.axios.get('zyOwner/zyOwnerFuzzyQuery/?' + this.qs.stringify(zyOwnerVO),
        {
          params: {
            currents: 1,
            sizes: 9999
          }
        })
        .then(res => {
          if (res.data.status === 'OK') {
            this.ownerList = res.data.data.records
          }
        })
    },
    // 查询小区信息
    async queryCommunityList() {
      const param = {
        'curr': 1,
        'size': 999999
        // 'communityName': this.communityName
      }
      const res = await listCommunity(param)
      this.communityList = res.data.records
    },
    querySysUserList() {
      const params = `current=1&size=9999`
      this.axios.get('/sysUser/page?' + params).then(res => {
        if (res.data.status === 'OK') {
          this.sysUserList = res.data.data.records
          if (this.sysUserList) {
            // 过滤掉超管
            this.sysUserList = this.sysUserList.filter(item => item.userName !== 'admin')
          }
        }
      })
    },
    // 添加按钮
    handleAdd() { // 打开对话框
      this.queryOwnerList()
      this.queryCommunityList()
      this.querySysUserList()
      this.repair.repairNum = get_one_uuid()
      this.dialogVisible = true
      this.flag = false
      this.title = '新增报修信息'
    },
    // 查看详情
    handleEdit(index, row) {
      this.value = row.repairState
      this.dialogVisible = true
      this.repair = JSON.parse(JSON.stringify(row))
      this.title = '修改'
    },
    // 保存修改
    saveForm() {
      if (!this.flag) {
        const user = this.sysUserList.filter(item => item.userId.toString() === this.repair.completeId.toString())
        this.repair.completeName = user[0].nickName
        this.axios.post('/zyRepair/add', this.repair).then(res => {
          if (res.data.data === 'ok') {
            this.$message.success('新增成功')
          } else {
            this.$message.error('新增失败,请联系管理员')
          }
        })
      } else if (this.flag) {
        this.repair.repairState = this.value

        this.axios({
          url: '/zyRepair/update',
          method: 'put',
          data: this.repair
        }).then(res => {
          if (res.data.data === 'ok') {
            this.$message.success('修改成功')
          } else {
            this.$message.error('修改失败')
          }
        })
      }
      this.loadZyRepairs(true)
      this.dialogVisible = false
    },

    // 类型翻译
    repairStatusFormat(row) {
      if (row.repairState === 'Pending') {
        return '待处理'
      } else if (row.repairState === 'Allocated') {
        return '已分派'
      } else if (row.repairState === 'Processing') {
        return '处理中'
      } else if (row.repairState === 'Processed') {
        return '已处理'
      } else if (row.repairState === 'No_Processed') {
        return '不处理'
      } else if (row.repairState === 'Cancelled') {
        return '已取消'
      }
    },

    // 全选
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 完整版 点击切换页数
    handleSizeChange(size) {
      this.pageSize = size
      this.current = 1
      this.loadZyRepairs()
    },
    // 点击    翻页
    handleCurrentChange(current) {
      this.current = current
      this.loadZyRepairs()
    },

    indexMethod(index) { // 序号
      index = (index + 1) + (this.current - 1) * this.pageSize
      return index
    },

    // 查询小区
    communityAll() {
      this.axios({
        url: 'http://localhost:8080/zyCommunity/listAll'
      }).then(res => {
        const list = res.data.data.map((item, index) => ({
          value: item.communityId,
          label: item.communityName
        }))
        this.community = list
      })
    },

    loadZyRepairs(flag) {
      this.formRepairs.current = this.current
      // 手动查询
      if (flag) {
        this.formRepairs.current = 1
      }
      this.formRepairs.size = this.pageSize
      // 首先分页查询
      this.axios.post('/zyRepair/getZyRepairsByPage', this.formRepairs).then(res => {
        if (res.data.status === 'OK') {
          this.repairs = res.data.data.records
          this.current = res.data.data.current
          this.total = res.data.data.total
          this.pageSize = res.data.data.size
        }
      })
    },

    // 重置表单数据
    resetForm(searchForm) {
      this.$refs[searchForm].resetFields()// 重置表单数据 <el-form-item  必须加 prop
      this.formRepairs.communityId = ''
      this.loadZyRepairs(true)
    },

    handleClose(done) { // 意外关闭
      // this.$confirm('确认关闭？')
      //   .then(_ => {
      //     done()
      //   })
      //   .catch(_ => {
      //   })
    },
    processCheck(index, row) {
      this.timeLineDataList = []
      this.repair = row
      const curRepairStateSort = this.Coptions.filter(item => item.value === row.repairState)[0].sort
      for (let i = 0; i < this.Coptions.length; i++) {
        const curStatusVal = this.Coptions[i]
        const timeLine = {}
        timeLine.stateVal = row.repairState
        timeLine.timestamp = row.createTime
        // #0bbd87
        if (curRepairStateSort >= curStatusVal.sort) {
          timeLine.color = '#0bbd87'
        }
        timeLine.sort = curStatusVal.sort
        timeLine.title = '报修状态：' + curStatusVal.label
        timeLine.content = this.getTimeLineContent(curStatusVal.value, row, timeLine, curRepairStateSort)
        timeLine.buttonVisible = false
        timeLine.buttonName = curStatusVal.buttonName
        // 如果是已处理（取消和本环节均不显示按钮）
        if (row.repairState === curStatusVal.value && row.repairState !== 'Processed') {
          timeLine.buttonVisible = true
          timeLine.clickFlag = curStatusVal.clickFlag
        }
        // 不处理环节按钮显示控制
        if (curStatusVal.value === 'No_Processed' && row.repairState !== 'Processed') {
          timeLine.buttonVisible = true
          timeLine.clickFlag = curStatusVal.clickFlag
        }
        // 当前为取消环节，所有按钮均不显示
        if (row.repairState === 'No_Processed') {
          timeLine.buttonVisible = false
        }
        this.timeLineDataList.push(timeLine)
      }
      this.progressVisible = true
    },
    getTimeLineContent(curStatusVal, row, timeLine, curRepairStateSort) {
      switch (curStatusVal) {
        case 'Pending':
          timeLine.attachContent = ''
          return row.createBy + ' 提交了报修单 ' + row.createTime
        case 'Allocated':
          if (curRepairStateSort >= timeLine.sort) {
            timeLine.attachContent = row.updateBy + ' 将报修单分派给 ' + row.assignmentId
            return row.updateBy + ' 修改了报修单 ' + row.createTime
          } else {
            return '暂未执行该环节，正在处理中，请等待 ...'
          }
        case 'Processing':
          if (curRepairStateSort >= timeLine.sort) {
            return row.completeName + ' 正在处理，联系方式 ' + row.completePhone
          } else {
            return '暂未执行该环节，正在处理中，请等待 ...'
          }

        case 'Processed':
          if (curRepairStateSort >= timeLine.sort) {
            return row.completeName + ' 已处理,处理时间 ' + row.completeTime
          } else {
            return '暂未执行该环节，正在处理中，请等待 ...'
          }

        case 'No_Processed':
          if (curRepairStateSort >= timeLine.sort) {
            timeLine.attachContent = row.updateBy + ' 将报修单分派给 ' + row.assignmentId
            return row.completeName + ' 不处理'
          } else {
            return '暂未执行该环节，正在处理中，请等待 ...'
          }

        case 'Cancelled':
          if (curRepairStateSort >= timeLine.sort) {
            timeLine.attachContent = row.updateBy + ' 将报修单分派给 ' + row.assignmentId
            return row.updateBy + ' 取消了报修单，取消时间 ' + row.cancelTime
          } else {
            return '暂未执行该环节，正在处理中，请等待 ...'
          }

        default:
          return ''
      }
    },
    processUpdate(clickFlag) {
      this.repair.repairState = clickFlag
      this.axios.put('/zyRepair/updateProcess', this.repair).then(res => {
        if (res.data.status === 'OK') {
          this.$message({
            type: 'success',
            message: '操作成功'
          })
        }
      }).finally(() => {
        this.loadZyRepairs()
        this.progressVisible = false
      })
    }
  }
}
</script>

<style scoped>

</style>
